package comp6231.project.replica.kelvin;

import java.nio.*;

public class Utils {

	/**
	 * Obtain a string from stream of bytes
	 * @param bb ByteBuffer
	 * @return String obtained from ByteBuffer
	 * @throws BufferUnderflowException
	 */
	public static String getString(ByteBuffer bb) throws BufferUnderflowException {
		int len = bb.getInt();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < len; i++) {
			sb.append(bb.getChar());
		}
		return sb.toString();
	}
	
	/**
	 * Serialize string into bytes stream
	 * @param bb ByteBuffer
	 * @param s String to be serialized
	 * @return Number of bytes string being serialized into
	 * @throws BufferOverflowException
	 * @throws ReadOnlyBufferException
	 */
	public static int putString(ByteBuffer bb, String s) throws 
		BufferOverflowException, ReadOnlyBufferException {
		int count = 0;
		bb.putInt(s.length());
		count += 4;
		for (int i = 0; i < s.length(); i++) {
			bb.putChar(s.charAt(i));
			count += 2;
		}
		return count;
	}
	
}
